var express = require('express')
,   core    = require("core")
,   crypto  = require("crypto")
,   router  = express.Router()
,   step    = core.step
,   utils   = core.utils
,   step    = core.step
,   send    = core.send
,   schema  = core.db.schema;

var GET = function(req, res, next) {
    var SEND = new send(0);
    var options = {
        config : req.app.config,
        authName : "管理员"
    };
    if(req.tokens.regAuth === 0)
        options.authName = "开发管理员";

    SEND.docs = options;

    res.render("register", SEND);
};

var POST = function(req, res, next){
    var query   = req.query
    ,   body    = req.body
    ,   token   = req.tokens
    ,   islogin = body.islogin
    ,   name    = body.name
    ,   pwd     = crypto.createHash('sha1')
    ,   auth    = token.regAuth
    ,   status  = token.status;


    pwd.update(body.pwd+"");
    pwd = pwd.digest('hex');

    var options = {
        name    : name,
        pwd     : pwd,
        auth    : auth,
        status  : status
    }
    ,   User = new schema.User(options);

    User.save(function(err, User){
        if(err)
            return next(new Error(new send(500001).msg));

        app.user.count += 1;

        if(!islogin)
            return res.redirect("/login");

        var sessions = {
            user : {
                uid     : User.uid,
                auth    : User.auth,
                image   : User.image
            }
        };

        res.session(sessions);

        return res.redirect("/home");

    });

};

/* GET home page. */
router.get('/', GET);
router.post('/', POST);

module.exports = router;
